<template>
    <div :class="{ hidden: hidden }" class="pagination-container">
        <el-pagination
            :background="background"
            v-model:current-page="currentPage"
            v-model:page-size="size"
            :layout="layout"
            :page-sizes="pageSizes"
            :pager-count="pagerCount"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { scrollTo } from "@/utils/scroll-to";
interface IProps {
    total: number;
    page?: number;
    limit?: number;
    pageSizes?: number[];
    pagerCount?: number;
    layout?: string;
    background?: boolean;
    autoScroll?: boolean;
    hidden?: boolean;
}

const props = withDefaults(defineProps<IProps>(), {
    page: 1,
    limit: 20,
    pageSizes: () => [10, 20, 30, 50],
    pagerCount: document.body.clientWidth < 992 ? 5 : 7,
    layout: "total, sizes, prev, pager, next, jumper",
    background: true,
    autoScroll: true,
    hidden: false,
});

const emit = defineEmits(["update:page", "pagination", "update:limit"]);
const currentPage = computed({
    get() {
        return props.page;
    },
    set(val) {
        emit("update:page", val);
    },
});
const size = computed({
    get() {
        return props.limit;
    },
    set(val) {
        emit("update:limit", val);
    },
});
function handleSizeChange(val: any) {
    if (currentPage.value * val > props.total) {
        currentPage.value = 1;
    }
    emit("pagination", { page: currentPage.value, limit: val });
    if (props.autoScroll) {
        scrollTo(0, 800, () => {});
    }
}
function handleCurrentChange(val: number) {
    emit("pagination", { page: val, limit: size.value });
    if (props.autoScroll) {
        scrollTo(0, 800, () => {});
    }
}
</script>

<style scoped>
.pagination-container {
    background: #fff;
    padding: 32px 16px;
}
.pagination-container.hidden {
    display: none;
}
</style>
